package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.plus.web.controller.BasePlusController;
import com.ruoyi.common.core.plus.web.page.PageDto;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.dto.UserInfo;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserForm;
import com.ruoyi.system.domain.params.SysUserParams;
import com.ruoyi.system.domain.vo.SysUserInfoVo;
import com.ruoyi.system.domain.vo.SysUserListVo;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BasePlusController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUserParams user) {
        PageDto pageDto = startPage();
        Page<SysUser> page = new Page(pageDto.getCurrentPage(), pageDto.getPageSize());
        Page<SysUser> sysUsers = userService.selectUserList(page,user);
/*        Page<SysUser> list = new Page<>();
        list.setRecords(sysUsers);*/
        Page<SysUserListVo> listVoList = sysUserToListVo(sysUsers);
        return getDataTable(listVoList);
    }

    public Page<SysUserListVo> sysUserToListVo(Page<SysUser> list) {
        Page<SysUserListVo> listVoList = new Page<SysUserListVo>(list.getCurrent(), list.getSize());
        List<SysUserListVo> records =new ArrayList<>();
        list.getRecords().forEach((item) -> {
            SysUserListVo sysUserListVo = BeanUtils.depthCopy(item, SysUserListVo.class);
            records.add(sysUserListVo);
        });
        listVoList.setRecords(records);
        listVoList.setTotal(list.getTotal());
        return listVoList;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserParams user) throws IOException {
        Page<SysUser> page = new Page<>(1, -1);
        Page<SysUser> list = (Page<SysUser>) userService.selectUserList(page,user);
        Page<SysUserListVo> listVoList = sysUserToListVo(list);
        ExcelUtil<SysUserListVo> util = new ExcelUtil<SysUserListVo>(SysUserListVo.class);
        util.exportExcel(response, listVoList.getRecords(), "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    public R<UserInfo> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }

        UserInfo userInfo = userService.SysUserToUserInfo(sysUser);
        return R.ok(userInfo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    /*@GetMapping("getInfo")
    public R<UserInfoVo> getInfo()
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("未找到用户信息");
        }
        UserInfo userInfo = userService.SysUserToUserInfo(sysUser);
        UserInfoVo userInfoVo = BeanUtils.depthCopy(userInfo,UserInfoVo.class);
        return R.ok(userInfoVo);
    }*/

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public R<SysUserInfoVo> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        /*AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", roleService.selectRoleAll());
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }*/
        SysUser sysUser = userService.selectUserById(userId);
        /** 角色组 */
        sysUser.setRoleList(roleService.selectRoleListByUserId(userId));
        sysUser.setPostList(postService.selectPostListByUserId(userId));
        SysUserInfoVo sysUserInfoVo = BeanUtils.depthCopy(sysUser, SysUserInfoVo.class);

        return R.ok(sysUserInfoVo);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysUserForm user) {

        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int insertUser = userService.insertUser(user);
        return R.ok(insertUser);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysUserForm user) {
//        userService.checkUserAllowed(user);
//        SysUser sysUser =new SysUser();
//        BeanUtils.copyProperties(user,sysUser);
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.updateUserStatus(user));
    }

    /**
     * 获取当前用户信息
     */
/*    @GetMapping("/info/dept_id_and_post_id/{deptId}/{postId}")
    public R<UserInfo> getInfoByDeptIdAndPostId(@PathVariable("deptId") Long deptId,@PathVariable("postId")Long postId)
    {
        SysUser sysUser = userService.getUserByDeptIdAndPostId(deptId,postId);
        if(sysUser==null){
            return R.ok();
        }
        UserInfo sysUserVo = userService.SysUserToUserInfo(sysUser);
        return R.ok(sysUserVo);
    }*/

    /**
     * 获取当前用户信息
     */
/*    @GetMapping("/info/dept_id_and_post_code/{deptId}/{postCode}")
    public R<UserInfo> getInfoByDeptIdAndPostCode(@PathVariable("deptId") Long deptId,@PathVariable("postCode")String postCode)
    {
        SysPost sysPost = postService.selectPostByCode(postCode);
        if(sysPost==null){
            return R.ok();
        }
        return getInfoByDeptIdAndPostId(deptId,sysPost.getPostId());
    }*/
}
